#!BPY

"""
Name: 'Aspect Engine (.model)'
Blender: 244
Group: 'Export'
Tooltip: 'Export a .model file of the currently selected (active) mesh object.'
"""
import Blender
import bpy
from Blender import Draw, BGL

def write_modelfile(filepath):
	out = file(filepath, 'w')
	# Getting last selected object in the scene. Will error if no objects are selected
	sce = bpy.data.scenes.active
	ob = sce.objects.active
	print ("Exporting %s to .model.\n" %(ob.name))
	# Getting object's linked datablock. We don't know it's a mesh. Will error if	it is not
	mesh = ob.getData(mesh=1)
	# Write header
	out.write('<?xml version="1.0" encoding=\'ISO-8859-1\'?>\n')
	out.write('<imf version="1.0">\n')
	# Write properties
	out.write('<properties>\n')
	out.write('<title>Title string.</title>\n')
	out.write('<description>Description string.</description>\n')
	out.write('<author>Author name.</author>\n')
	out.write('<defaultmaterial name="Example.material" path="./"/>\n')
	out.write('</properties>\n')
	# Ensure mesh has no quads, only tris
	mesh.quadToTriangle()
	# Begin triangles
	out.write('<triangles>\n')
	# Write triangle data
	for face in mesh.faces:
		tvcount = 0
		out.write('<triangle>\n')
		for vert in face.verts:
			if mesh.faceUV:
				out.write( '<vertex posx="%f" posy="%f" posz="%f" normx="%f" normy="%f" normz="%f" u="%f" v="%f"/>\n' % (vert.co.x, vert.co.y, vert.co.z, vert.no.x, vert.no.y, vert.no.z, face.uv[tvcount][0], face.uv[tvcount][1]) )
			else:
				out.write( '<vertex posx="%f" posy="%f" posz="%f" normx="%f" normy="%f" normz="%f" u="0" v="0"/>\n' % (vert.co.x, vert.co.y, vert.co.z, vert.no.x, vert.no.y, vert.no.z) )
			tvcount = tvcount+1
		out.write('</triangle>\n')
	out.write('</triangles>\n')
	out.write('</imf>')
	out.close()
Blender.Window.FileSelector(write_modelfile, "Export", "%s.model" %(bpy.data.scenes.active.objects.active.name))
print ("Done.\n")